package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.train.MoreActivities.MoreSpecialActivity;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.PeopleItem;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class StationPeopleActivity extends ListActivity{
	private ArrayList<JSONObject> json_list;
	private ArrayList<PeopleItem> list;
	private PeopleAdapter nadapter;
	private TextView station;
	private ImageButton board, table, info, write;
	private ImageView back;
	private String stationId, station_name;
	private WebView bannerWebView;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.station_people);
        board = (ImageButton)findViewById(R.id.btnShowProfile);
        table = (ImageButton)findViewById(R.id.btnShowSchedule);
        info = (ImageButton)findViewById(R.id.btnShowStationAbout);
        write = (ImageButton)findViewById(R.id.add_board);
	    list = new ArrayList<PeopleItem>();
	    json_list = new ArrayList<JSONObject>();
        Intent intent = getIntent();
        stationId = intent.getExtras().get("station_id").toString();
        station_name = intent.getExtras().get("station_name").toString();
	    bannerWebView = (WebView) findViewById(R.id.banner);
		bannerWebView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url){
				String[] values = url.split("!");
				if(values[1].equals("app")){
					if(values[2].equals("live")){
						Intent intent = new Intent(getBaseContext(), AllBoardActivity.class);
						startActivity(intent);
						
					}
					else if(values[2].equals("enjoy")){
						Intent intent = new Intent(getBaseContext(), MoreSpecialActivity.class);
						startActivity(intent);
					}
				}
				else if(values[1].equals("board")){
					ActivityGroup parentActivity = (ActivityGroup) getParent();
					Intent intent = new Intent(getBaseContext(), BoardViewActivity.class);
					intent.putExtra("board_id", values[2]);
					intent.putExtra("station_id", stationId);
					intent.putExtra("station_name", station_name);
					((FavoriteActivity) parentActivity).startChildActivity("BoardView", intent);
				}
				else if(values[1].equals("web")){
					Intent intent = new Intent(Intent.ACTION_VIEW); 
					Uri uri = Uri.parse(values[2]); 
					intent.setData(uri); 
					startActivity(intent);
				}
				return true;
			}
		});
		bannerWebView.loadUrl(ServerURL.bannerWebView(stationId,
													  Preferences.getValue(getBaseContext(), "device_token"),
													  Preferences.getValue(getBaseContext(), "user_id"),
													  Preferences.getValue(getBaseContext(), "version")));
        station = (TextView)findViewById(R.id.stationName);
		back = (ImageView)findViewById(R.id.btnBack);
		station.setText(station_name + "역");
		setClickListener();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}

	private void setListView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.downloadPeopleFromStation, "station_id", stationId, "user_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}

	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});
		}
	}
	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			try {
				JSONObject nobject = new JSONObject(urls[0]);
				JSONArray json_arr = new JSONArray(nobject.getString("users"));
				PeopleItem input;
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					json_list.add(json_obj);
					Bitmap image_url = null;
					if(!json_obj.get("image_thumb_url").toString().equals("null") && !json_obj.get("image_thumb_url").toString().equals("")){
						image_url = LoadBitMap.fromURL(json_obj.get("image_thumb_url").toString());
					}
					input = new PeopleItem(image_url, json_obj.get("nick_name").toString());
					list.add(input);
				}
				
			} catch(JSONException e){
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			nadapter = new PeopleAdapter(getBaseContext(), R.layout.favorite_people_row, list);
		    ListView lv = getListView();
		    lv.setAdapter(nadapter);
		}
	}


	
	public void setClickListener(){
		back.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		board.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), StationBoardActivity.class);
				intent.putExtra("station_id", stationId);
				intent.putExtra("station_name", station_name);
				((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("StationBoard", intent);
			}
		});
		table.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), StationScheduleActivity.class);
				intent.putExtra("station_id", stationId);
				intent.putExtra("station_name", station_name);
				((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("StationSchedule", intent);
			}
		});
		info.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), StationInfoActivity.class);
				intent.putExtra("station_id", stationId);
				intent.putExtra("station_name", station_name);
				((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("StationInfo", intent);
			}
		});
		write.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getBaseContext(), BoardWriteActivity.class);
				intent.putExtra("station_id", stationId);
				intent.putExtra("station_name", station_name);
				startActivity(intent);
				}
		});
		
	}

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		try {
			JSONObject output = json_list.get(position);
			String out = (String)output.get("user_id");
			ActivityGroup parentActivity = (ActivityGroup) getParent();
			Intent intent = new Intent(getBaseContext(), EachProfileActivity.class);
			intent.putExtra("user_id", out);
			((FavoriteActivity) parentActivity).startChildActivity("EachProfile", intent);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

	private class PeopleAdapter extends ArrayAdapter<PeopleItem>{
		private ArrayList<PeopleItem> items;
		private int layout;
		
		public PeopleAdapter(Context ctx, int rsrcId, ArrayList<PeopleItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.layout = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			PeopleItem e = items.get(position);
			if(e != null){

				ImageView image = ((ImageView)v.findViewById(R.id.userPic));
				if(e.getImage() != null){
					image.setImageBitmap(e.getImage());
				}
				else{
					image.setImageResource(R.drawable.icon_noprofile_m);
				}
				((TextView)v.findViewById(R.id.favorite_user_id)).setText(e.getName());
			}
			return v;
		}
	}

}
